import axios from 'axios'

const API_BASE_URL = 'http://localhost:5000/api'

// 创建axios实例
const carApi = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
carApi.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
carApi.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// API接口定义
export const carApiService = {
  // 获取所有品牌
  getAllBrands() {
    return carApi.get('/brands')
  },
  
  // 获取热门品牌
  getPopularBrands(limit = 8) {
    return carApi.get(`/brands/popular?limit=${limit}`)
  },
  
  // 根据品牌ID获取车型列表
  getCarsByBrand(brandId, page = 1, perPage = 10) {
    return carApi.get(`/brands/${brandId}/cars?page=${page}&per_page=${perPage}`)
  },
  
  // 获取品牌下的热门车型
  getPopularCarsByBrand(brandId, limit = 5) {
    return carApi.get(`/brands/${brandId}/cars/popular?limit=${limit}`)
  },
  
  // 搜索车型
  searchCars(keyword, page = 1, perPage = 10) {
    return carApi.get(`/cars/search?keyword=${encodeURIComponent(keyword)}&page=${page}&per_page=${perPage}`)
  },
  
  // 获取车型详情
  getCarDetail(carId) {
    return carApi.get(`/cars/${carId}`)
  },
  
  // 获取所有车型（支持分页和筛选）
  getCars(params = {}) {
    const queryParams = new URLSearchParams()
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
        queryParams.append(key, params[key])
      }
    })
    return carApi.get(`/cars?${queryParams.toString()}`)
  },
  
  // 获取筛选选项数据
  getFilterOptions() {
    return carApi.get('/brands')
  }
}

export default carApiService